// i18n 配置文件
import i18next from 'https://cdn.skypack.dev/i18next';
import LanguageDetector from 'https://cdn.skypack.dev/i18next-browser-languagedetector';

// 翻译资源
const resources = {
  zh: {
    translation: {
      "welcome": "欢迎使用i18n国际化示例",
      "description": "这是一个学习国际化的演示项目",
      "language": "语言",
      "home": "首页",
      "about": "关于我们",
      "contact": "联系方式",
      "username": "用户名",
      "password": "密码",
      "login": "登录",
      "logout": "退出",
      "hello": "你好，{{name}}！",
      "current_time": "当前时间：{{time}}",
      "item_count": "你有 {{count}} 个项目",
      "item_count_plural": "你有 {{count}} 个项目",
      "footer_text": "版权所有 © 2024 i18n演示项目"
    }
  },
  en: {
    translation: {
      "welcome": "Welcome to i18n Internationalization Demo",
      "description": "This is a demo project for learning internationalization",
      "language": "Language",
      "home": "Home",
      "about": "About Us",
      "contact": "Contact",
      "username": "Username",
      "password": "Password",
      "login": "Login",
      "logout": "Logout",
      "hello": "Hello, {{name}}!",
      "current_time": "Current time: {{time}}",
      "item_count": "You have {{count}} item",
      "item_count_plural": "You have {{count}} items",
      "footer_text": "Copyright © 2024 i18n Demo Project"
    }
  },
  ja: {
    translation: {
      "welcome": "i18n国際化デモへようこそ",
      "description": "これは国際化を学習するためのデモプロジェクトです",
      "language": "言語",
      "home": "ホーム",
      "about": "私たちについて",
      "contact": "お問い合わせ",
      "username": "ユーザー名",
      "password": "パスワード",
      "login": "ログイン",
      "logout": "ログアウト",
      "hello": "こんにちは、{{name}}さん！",
      "current_time": "現在時刻：{{time}}",
      "item_count": "{{count}}個のアイテムがあります",
      "item_count_plural": "{{count}}個のアイテムがあります",
      "footer_text": "著作権 © 2024 i18nデモプロジェクト"
    }
  }
};

// i18next 初始化
i18next
  .use(LanguageDetector)
  .init({
    resources,
    fallbackLng: 'en', // 默认语言
    debug: true, // 开发时开启调试

    detection: {
      // 语言检测配置
      order: ['localStorage', 'navigator', 'htmlTag'],
      caches: ['localStorage'],
    },

    interpolation: {
      escapeValue: false // React已经默认转义了
    }
  });

// 更新页面内容的函数
function updateContent() {
  // 更新所有带有 data-i18n 属性的元素
  document.querySelectorAll('[data-i18n]').forEach(element => {
    const key = element.getAttribute('data-i18n');
    element.textContent = i18next.t(key);
  });

  // 更新所有带有 data-i18n-placeholder 属性的元素
  document.querySelectorAll('[data-i18n-placeholder]').forEach(element => {
    const key = element.getAttribute('data-i18n-placeholder');
    element.placeholder = i18next.t(key);
  });

  // 更新动态内容示例
  updateDynamicContent();
}

// 更新动态内容
function updateDynamicContent() {
  // 问候语示例（插值）
  const helloElement = document.getElementById('hello-message');
  if (helloElement) {
    helloElement.textContent = i18next.t('hello', { name: '小明' });
  }

  // 时间示例
  const timeElement = document.getElementById('current-time');
  if (timeElement) {
    const now = new Date().toLocaleString();
    timeElement.textContent = i18next.t('current_time', { time: now });
  }

  // 复数示例
  const countElement = document.getElementById('item-count');
  if (countElement) {
    const count = Math.floor(Math.random() * 10) + 1;
    countElement.textContent = i18next.t('item_count', { count });
  }
}

// 语言切换函数
function changeLanguage(lng) {
  i18next.changeLanguage(lng, (err, t) => {
    if (err) {
      console.error('语言切换失败:', err);
      return;
    }
    console.log('语言已切换到:', lng);
    updateContent();

    // 更新语言选择器的选中状态
    const languageSelect = document.getElementById('language-select');
    if (languageSelect) {
      languageSelect.value = lng;
    }
  });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
  // 初始化内容
  updateContent();

  // 设置语言选择器的初始值
  const languageSelect = document.getElementById('language-select');
  if (languageSelect) {
    languageSelect.value = i18next.language;

    // 添加语言切换事件监听器
    languageSelect.addEventListener('change', (e) => {
      changeLanguage(e.target.value);
    });
  }

  // 设置刷新按钮事件
  const refreshBtn = document.getElementById('refresh-btn');
  if (refreshBtn) {
    refreshBtn.addEventListener('click', updateDynamicContent);
  }
});

// 导出全局函数
window.i18next = i18next;
window.changeLanguage = changeLanguage;
window.updateContent = updateContent;